package com.video.mall.controller;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.video.common.config.RestHighLeveConfig;
import com.video.common.domain.QueryPageDto;
import com.video.common.enumeration.AppHttpCodeEnum;
import com.video.common.result.PageResult;
import com.video.common.result.ResponseResult;
import com.video.mall.domain.dto.ProductDto;
import com.video.mall.domain.entity.ProductSwipe;
import com.video.mall.domain.entity.Standard;
import com.video.mall.service.IProductService;
import lombok.RequiredArgsConstructor;
import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 前端控制器
 * </p>
 *
 * @author la
 * @since 2024-11-19
 */
@RestController
@RequestMapping("/product")
@RequiredArgsConstructor
public class ProductController {

    private final IProductService productService;

    private final RestHighLeveConfig config;

    /*
     * 查询商品列表
     * */
    @GetMapping("/list")
    public ResponseResult shopList(QueryPageDto dto) throws IOException {
        RestHighLevelClient client = config.restHighLevelClient();
        PageResult result = productService.queryList(dto, client);
        return ResponseResult.okResult(result);
    }

    /*
     * 新增或编辑商品信息
     * */
    @PostMapping("/update")
    public ResponseResult saveOrUpdate(@RequestBody ProductDto product) throws IOException {
        // 建立es连接
        RestHighLevelClient client = config.restHighLevelClient();

        // 判断index是否存在
        GetIndexRequest getIndexRequest = new GetIndexRequest("product");
        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);

        if (!exists) {
            // 创建index
            CreateIndexRequest request = new CreateIndexRequest("product");

            // 使用 ClassPathResource 读取文件
            String mappingTemplate;
            ClassPathResource resource = new ClassPathResource("es-template/goods-template.json");
            // 读取文件模版
            try (InputStream inputStream = resource.getInputStream()) {
                mappingTemplate = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
            }
            // 添加源
            request.source(mappingTemplate, XContentType.JSON);
            // 创建index
            client.indices().create(request, RequestOptions.DEFAULT);
        }

        ResponseResult result = productService.saveOrUpdateProduct(product, client);

        return ResponseResult.okResult(result);
    }


    /*
     * 删除接口
     * */
    @Transactional
    @DeleteMapping("/{id}")
    public ResponseResult delete(@PathVariable Long id) throws IOException {
        // 创建es连接
        RestHighLevelClient client = config.restHighLevelClient();

        // 删除es对应的数据
        DeleteRequest deleteRequest = new DeleteRequest("product", String.valueOf(id));

        client.delete(deleteRequest, RequestOptions.DEFAULT);

        // 删除数据库对应数据
        productService.removeById(id);

        // 删除关联轮播及规格数据
        List<ProductSwipe> swipeList = Db.lambdaQuery(ProductSwipe.class).list();
        List<Long> swipeCollect = swipeList.stream().map(ProductSwipe::getId).collect(Collectors.toList());
        List<Standard> standards = Db.lambdaQuery(Standard.class).eq(Standard::getProductId, id).list();
        List<Long> standardCollect = standards.stream().map(Standard::getId).collect(Collectors.toList());

        if (CollUtil.isNotEmpty(swipeCollect)) {
            Db.removeByIds(swipeCollect, ProductSwipe.class);
        }

        if (CollUtil.isNotEmpty(standardCollect)) {
            Db.removeByIds(standardCollect, Standard.class);
        }

        // 在更新数据后，手动刷新索引以确保数据立即可见：
        client.indices().refresh(new RefreshRequest("product"), RequestOptions.DEFAULT);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
